using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Tewux.Peer2Image
{
	public class Settings
	{
		// ustawienia kodownia
		public string Password;
		public List<string> BackImages;
		public CodingMethod CodingMode;
		public int MaxImageSize;
		// ustawienia dekodowania
		public string DownloadDir;

		// stale
		const string defaultBackImage = "backimages\\example.jpg";
		static string defaultDownloadDir = Application.StartupPath + "\\download";

		public Settings()
		{
			Password = String.Empty;
			BackImages = new List<string>();
			BackImages.Add(defaultBackImage);
			CodingMode = CodingMethod.Mode1;
			MaxImageSize = 1024 * 1024;
			DownloadDir = defaultDownloadDir;
		}

		public void Save()
		{
			XmlSerializer xml = new XmlSerializer(typeof(Settings));
			XmlTextWriter writer = new XmlTextWriter("settings.xml", Encoding.UTF8);
			writer.Formatting = Formatting.Indented;
			xml.Serialize(writer, this);
		}

		static public Settings Load()
		{
			XmlSerializer xml = new XmlSerializer(typeof(Engine));
			XmlTextReader reader = new XmlTextReader("settings.xml");
			Settings obj = (Settings)xml.Deserialize(reader);

			if (!Directory.Exists(obj.DownloadDir))
				obj.DownloadDir = defaultDownloadDir;

			foreach (string filename in obj.BackImages)
				if (!File.Exists(filename))
					obj.BackImages.Remove(filename);

			if (obj.BackImages.Count < 1)
				obj.BackImages.Add(defaultBackImage);

			return obj;
		}

		private int nextBackImage = 0;
		public Bitmap GetBackImage()
		{
			try
			{
				Bitmap bmp;
				if (nextBackImage < BackImages.Count)
				{
					bmp = (Bitmap)Bitmap.FromFile(BackImages[nextBackImage]);
				}
				else
				{
					nextBackImage = 0;
					bmp = (Bitmap)Bitmap.FromFile(BackImages[nextBackImage]);
				}
				nextBackImage = (nextBackImage + 1) % BackImages.Count;
				return bmp;
			}
			catch
			{
				return (Bitmap)Bitmap.FromFile(defaultBackImage);
			}
		}
	}

	public enum CodingMethod
	{
		CleanData = 0, Mode1, Mode2
	}

}
